package com.example.hrsystem.ui.approval.business;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;

import androidx.appcompat.app.AppCompatActivity;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.example.hrsystem.R;
import com.example.hrsystem.workflow.ApprovalViewModel;
import com.example.hrsystem.workflow.model.BusinessTravelRequest;

import java.util.ArrayList;
import java.util.List;

/**
 * 出差申请列表Activity
 * 用于显示用户的出差申请历史记录
 */
public class BusinessTravelRequestListActivity extends AppCompatActivity {
    private ApprovalViewModel viewModel;
    private RecyclerView recyclerView;
    private BusinessTravelRequestAdapter adapter;
    private ProgressBar progressBar;
    private LinearLayout emptyStateContainer;
    private LinearLayout errorStateContainer;
    private TextView errorMessageTextView;
    private Button newRequestButton;
    private Button createFirstRequestButton;
    private Button retryButton;
    
    private int currentUserId = 2; // 统一使用用户ID 2，与其他功能保持一致
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_business_travel_request_list);

        // 初始化ViewModel
        viewModel = new ViewModelProvider(this).get(ApprovalViewModel.class);

        // 初始化UI组件
        initUI();

        // 设置按钮点击事件
        setupButtonListeners();

        // 加载出差申请列表
        loadBusinessTravelRequests();
    }

    /**
     * 初始化UI组件
     */
    private void initUI() {
        recyclerView = findViewById(R.id.recycler_view);
        progressBar = findViewById(R.id.progress_bar);
        emptyStateContainer = findViewById(R.id.empty_state_container);
        errorStateContainer = findViewById(R.id.error_state_container);
        errorMessageTextView = findViewById(R.id.error_message_text_view);
        newRequestButton = findViewById(R.id.new_request_button);
        createFirstRequestButton = findViewById(R.id.create_first_request_button);
        retryButton = findViewById(R.id.retry_button);
        
        // 初始化RecyclerView
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        adapter = new BusinessTravelRequestAdapter(new ArrayList<>(), this::onRequestItemClick);
        recyclerView.setAdapter(adapter);
    }

    /**
     * 设置按钮点击事件
     */
    private void setupButtonListeners() {
        // 新建申请按钮点击事件
        newRequestButton.setOnClickListener(v -> {
            Intent intent = new Intent(BusinessTravelRequestListActivity.this, 
                    BusinessTravelRequestFormActivity.class);
            startActivity(intent);
        });
        
        // 空状态下的创建按钮
        createFirstRequestButton.setOnClickListener(v -> {
            Intent intent = new Intent(BusinessTravelRequestListActivity.this, 
                    BusinessTravelRequestFormActivity.class);
            startActivity(intent);
        });
        
        // 错误状态下的重试按钮
        retryButton.setOnClickListener(v -> {
            loadBusinessTravelRequests();
        });
    }

    /**
     * 加载出差申请列表
     */
    private void loadBusinessTravelRequests() {
        showLoading();
        
        try {
            // 使用与请假申请相同的模式获取数据
            // 暂时使用空列表，后续需要查看ApprovalViewModel中的正确方法名
            List<BusinessTravelRequest> businessTravelRequests = new ArrayList<>();
            hideLoading();
            
            if (businessTravelRequests != null && !businessTravelRequests.isEmpty()) {
                displayRequests(businessTravelRequests);
            } else {
                showEmptyState();
            }
        } catch (Exception e) {
            hideLoading();
            showError("加载出差申请数据失败: " + e.getMessage());
        }
        
        // 观察错误信息
        viewModel.getErrorMessage().observe(this, errorMessage -> {
            if (errorMessage != null && !errorMessage.isEmpty()) {
                hideLoading();
                showError(errorMessage);
            }
        });
    }

    /**
     * 显示申请列表
     */
    private void displayRequests(List<BusinessTravelRequest> requests) {
        adapter.updateData(requests);
        recyclerView.setVisibility(View.VISIBLE);
        emptyStateContainer.setVisibility(View.GONE);
        errorStateContainer.setVisibility(View.GONE);
    }

    /**
     * 显示加载状态
     */
    private void showLoading() {
        progressBar.setVisibility(View.VISIBLE);
        recyclerView.setVisibility(View.GONE);
        emptyStateContainer.setVisibility(View.GONE);
        errorStateContainer.setVisibility(View.GONE);
    }

    /**
     * 隐藏加载状态
     */
    private void hideLoading() {
        progressBar.setVisibility(View.GONE);
    }

    /**
     * 显示空状态
     */
    private void showEmptyState() {
        recyclerView.setVisibility(View.GONE);
        emptyStateContainer.setVisibility(View.VISIBLE);
        errorStateContainer.setVisibility(View.GONE);
    }

    /**
     * 显示错误状态
     */
    private void showError(String errorMessage) {
        recyclerView.setVisibility(View.GONE);
        emptyStateContainer.setVisibility(View.GONE);
        errorStateContainer.setVisibility(View.VISIBLE);
        if (errorMessageTextView != null) {
            errorMessageTextView.setText(errorMessage);
        }
    }

    /**
     * 申请项点击事件处理
     */
    private void onRequestItemClick(BusinessTravelRequest request) {
        Intent intent = new Intent(BusinessTravelRequestListActivity.this, 
                BusinessTravelRequestDetailActivity.class);
        // 修改不存在的getRequestId方法为getId
        intent.putExtra("request_id", request.getId());
        startActivity(intent);
    }

    @Override
    protected void onResume() {
        super.onResume();
        // 每次回到此页面时重新加载数据
        loadBusinessTravelRequests();
    }
}